<template>
  <div id="teamAddPage">
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <!--队伍名称-->
      <van-field
          v-model="addTeamData.name"
          name="name"
          label="队伍名称"
          placeholder="请输入队伍名称"
          :rules="[{ required: true, message: '请输入队伍名称' }]"
      />
      <!--队伍描述-->
      <van-field
          v-model="addTeamData.description"
          rows="4"
          autosize
          label="队伍描述"
          type="textarea"
          placeholder="请输入队伍描述"
      />
      <!--过期时间-->
      <van-field
          v-model="addTeamData.expireTime"
          is-link
          readonly
          name="datePicker"
          label="过期时间"
          placeholder="点击选择过期时间"
          @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" position="bottom">
        <van-picker-group
          title="设定过期日期"
          :tabs="['选择日期', '选择时间']"
          @confirm="onConfirm"
          @cancel="showPicker = false"
          >
          <van-date-picker
            v-model="currentDate"
            :min-date="minDate"
            />
          <van-time-picker
            v-model="currentTime"
            :columns-type="columnsType"
            />
        </van-picker-group>
      </van-popup>
      <!--队伍状态-->
    <van-field name="radio" label="队伍状态">
      <template #input>
        <van-radio-group v-model="addTeamData.status" direction="horizontal">
          <van-radio name="0">公开</van-radio>
          <van-radio name="1">私有</van-radio>
          <van-radio name="2">加密</van-radio>
        </van-radio-group>
      </template>
    </van-field>
      <!--队伍密码-->
    <van-field
        v-if="Number(addTeamData.status) === 2"
        v-model="addTeamData.password"
        type="password"
        name="userPassword"
        label="密码"
        placeholder="请输入队伍密码"
        :rules="[{ required: true, message: '请填写密码' }]"
    />
    <van-uploader v-model="fileList"
                  :after-read="onAfterRead"
                  accept="image/png, image/jpeg"
                  multiple :max-count="1"
                  :max-size="500 * 1024"
    />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showFailToast, showLoadingToast, showSuccessToast} from "vant";
import {useRoute, useRouter} from "vue-router";
import dateFormat from "../plugins/dateFormat";

const router = useRouter();
const route = useRoute();

//展示日期选择器
const showPicker = ref(false)

const minDate = new Date();

//定义一个初始时间(年月日)
const currentDate = ref(['2023', '02', '09']);
//定义一个初始时间(时分秒)
const currentTime = ref(['12', '00', '00']);
const columnsType = ['hour', 'minute', 'second'];

//队伍Id
const id = route.query.id;

/**
 * 获取之前队伍信息
 */
onMounted(async () => {
  if (id <= 0){
    showFailToast("队伍加载失败");
    return;
  }
  const res = await myAxios.get("/team/get", {
    params: {
      id: id,
    }
  });
  if (res?.code === 0){
      addTeamData.value = res.data;
      //将过期时间进行转换再展示
      addTeamData.value.expireTime = dateFormat(res.data.expireTime);
      console.log("date= " + res.data.expireTime)
  }else {
    showFailToast("队伍加载失败，请刷新重试");
  }
})

const onConfirm = () => {
  addTeamData.value.expireTime = currentDate.value.join('-') + " " + currentTime.value.join(":");
  showPicker.value = false;  //有了这行才会使picker点击确认后自动关闭
}

//需要用户添加的表单数据
const addTeamData = ref({})

/**
 * 将 String的时间格式转换为 Date格式
 * @param str
 * @returns {Date}
 */
const strChangeDate = (str) =>{
  return new Date(str);
}

/**
 * 提交
 * @returns {Promise<void>}
 */
const onSubmit = async () =>{
  const postData = {
    ...addTeamData.value,
    status: Number(addTeamData.value.status),
    expireTime: strChangeDate(addTeamData.value.expireTime)
  }
  //参数校验
  const res = await myAxios.post("/team/update", postData);
  if (res?.code === 0 && res.data){
    showSuccessToast("更新成功");
    router.push({
      path: "/team",
      replace: true,
    });
  }else {
    console.log("time= " + (addTeamData.value.expireTime))
    showFailToast("更新失败")
  }
}

/**
 * 更换队伍头像
 * @type {Ref<UnwrapRef<*[]>>}
 */
const fileList = ref([]);

const onAfterRead = async (file) =>{
  const formData = new FormData();
  formData.append('file', file.file);
  console.log("file= " + file);
  // currentUserId.value = currentUser.id;
  // avatarUrl.value = file.content;
  const res = myAxios.post('/team/updateTeamUrl', {
    "file": formData.get("file"),
    "teamId": id
  }, {
    headers:  {
      "content-type": "multipart/form-data",
    },
  })
      .then(function (response){
        console.log("/team/updateTeamUrl success= " + response);
        // showSuccessToast('请求成功');
      })
      .catch(function (error) {
        console.log('/team/updateTeamUrl error', error);
        // showFailToast('请求失败');
      })
  if (res.code == 0){
    // showSuccessToast("图片成功");;
  }
}
</script>

<style scoped>

</style>